//控制器层

const { QueryTypes, Op } = require("sequelize");

const path = require("path");

const uuid = require("uuid");

let utils = require(path.resolve(__basename, "utils/utils.js"));

class Controller {
  constructor() {}
  //测试接口
  text(req, res) {
    res.send("ok");
  }
  //发送验证码
  sendValidCode(req, res) {
    let validCode = utils.createSixValidCode();
    // console.log("validCode ==> ", validCode);
    // console.log("req.body.email ==> ", req.body.email);

    //生成验证码id
    let validCodeId = uuid.v1();
    // console.log("validCodeId ==> ", validCodeId);
    model.ValidCode.create({
      validCodeId,
      email: req.body.email,
      validCode,
    })
      .then((result) => {
        console.log("result==>", result);
        res.send({ msg: "发送验证码成功", code: 1000, validCodeId });
      })
      .catch((err) => {
        console.log("err==>", err);
        res.send({ msg: "发送验证码失败", code: 1001 });
      });

    // 开发屏蔽发邮件
    return;

    utils
      .sendEmail({
        emails: req.body.email,
        subject: "邮箱验证码",
        text: `验证码为：${validCode}，5分钟内有效。`,
      })
      .then((result) => {
        console.log("result==>", result);

        //保存验证码到数据库

        //生成验证码
        let validCodeId = uuid.v1();
        model.ValidCode.create({
          validCodeId,
          email: req.body.email,
          validCode,
        })
          .then((result) => {
            console.log("result==>", result);
            res.send({ msg: "发送验证码成功", code: 1000, validCodeId });
          })
          .catch((err) => {
            console.log("err==>", err);
            res.send({ msg: "发送验证码失败", code: 1001 });
          });
      })
      .catch((err) => {
        console.log("err==>", err);
        res.send({ msg: "发送验证码失败", code: 1001 });
      });
  }
  //注册接口
  async register(req, res) {
    let user = await model.User.findOne({
      //查数据
      where: {
        email: req.body.email,
      },
    });
    // console.log("user==>", user);
    if (!user) {
      let userId = uuid.v1();
      let password = utils.encodeString(req.body.password);
      //注册新用户
      model.User.create({
        userId,
        email: req.body.email,
        password,
      })
        .then((result) => {
          // console.log("result==>", result);
          res.send({ msg: "邮箱注册成功", code: 1020 });
        })
        .catch((err) => {
          console.log("err==>", err);
          res.send({ msg: "邮箱注册失败", code: 1022 });
        });
    } else {
      res.send({ msg: "邮箱已注册", code: 1021 });
    }
    // res.send("注册成功！！！");
  }
  //登录
  login(req, res) {
    // console.log(req.body);
    model.User.findOne({
      attributes: ["userId", "password"],
      where: {
        email: req.body.email,
      },
    })
      .then((result) => {
        // console.log("result==>", result);
        if (result) {
          let password = utils.encodeString(req.body.password);
          // console.log(password);
          // console.log(result.dataValues.password);
          if (password === result.dataValues.password) {
            //生成token
            let token = utils.signToken(result.dataValues.userId);

            res.send({ msg: "登录成功", code: 1030, token });
          } else {
            res.send({ msg: "邮箱或者密码错误", code: 1033 });
          }
        } else {
          res.send({ msg: "邮箱未注册", code: 1032 });
        }
      })
      .catch((err) => {
        console.log("err==>", err);
        res.send({ msg: "登录失败", code: 1031 });
      });
  }
  //创建商品类型
  createType(req, res) {
    let typeId = uuid.v1();
    // console.log("req.body==>", req.body);
    //创建商品类型
    // console.log("typeId==>", typeId);
    //启动事务处理
    sequelize.transaction(async (t) => {
      //1、创建商品类型
      await model.Type.create(
        {
          name: req.body.name,
          typeId,
        },
        { transaction: t }
      );
      //2、创建用户和商品类型的关系
      await model.UserType.create(
        {
          typeId,
          userId: req.userId,
        },
        { transaction: t }
      )
        .then((result) => {
          console.log("result==>", result);
          res.send({ msg: "创建成功", code: 1050 });
        })
        .catch((err) => {
          console.log("err==>", err);
          res.send({ msg: "创建失败", code: 1051 });
        });
    });
  }
  //获取用户信息
  getUserInfo(req, res) {
    // console.log("req.userId==>", req.userId);
    model.User.findOne({
      attributes: ["email", "user_img"],
      where: {
        userId: req.userId,
      },
    })
      .then((result) => {
        console.log("result==>", result);
        res.send({ msg: "获取用户数据成功", code: 1200, result });
      })
      .catch((err) => {
        console.log("err==>", err);
        res.send({ msg: "获取用户数据失败", code: 1201 });
      });
  }
  //搜索【查询商品类型】
  findTypeList(req, res) {
    // res.send("ok");
    // console.log("req.query==>", req.query);

    let sql =
      "SELECT `ut`.`type_id` AS `typeId`, `ut`.`user_id` AS `userId`, `t`.`name`, `t`.`created_at` AS `createdAt` FROM `user_type` AS `ut` INNER JOIN `type` AS `t` ON `t`.`type_id` = `ut`.`type_id` AND `ut`.`user_id` = :userId";
    //替换sql语句的参数
    let replacements = {
      userId: req.userId,
      offset: Number(req.query.offset),
      limit: Number(req.query.limit),
    };

    //判断是否根据商品类型关键字进行搜索
    if (req.query.name) {
      sql += " AND `t`.`name` LIKE :name";
      replacements.name = `%${req.query.name}%`;
    }

    //判断是否根据创建日期关进行搜索
    if (req.query.createdAt) {
      sql += " AND `t`.`created_at` >= :start AND `t`.`created_at` <= :end";
      replacements.start = `${req.query.createdAt}`;
      replacements.end = `${req.query.createdAt.split(" ")[0]} 23:59:59`;
    }

    sql += " ORDER BY `t`.`created_at` DESC LIMIT :offset, :limit";

    sequelize
      .query(sql, {
        replacements,
        type: QueryTypes.SELECT,
      })
      .then((result) => {
        res.send({ msg: "查询商品类型成功", code: 1060, result });
      })
      .catch((err) => {
        res.send({ msg: "查询商品类型失败", code: 1061 });
      });
  }
  //查询商品类型总数据量
  getAllTypeCount(req, res) {
    // res.send("ok");
    // console.log("req.query==>", req.query);

    let sql =
      "SELECT COUNT(`t`.`type_id`) AS `count` FROM `user_type` AS `ut` INNER JOIN `type` AS `t` ON `t`.`type_id` = `ut`.`type_id` AND `ut`.`user_id` = :userId";
    //替换sql语句的参数
    let replacements = {
      userId: req.userId,
    };

    //判断是否根据商品类型关键字进行搜索
    if (req.query.name) {
      sql += " AND `t`.`name` LIKE :name";
      replacements.name = `%${req.query.name}%`;
    }

    //判断是否根据创建日期关进行搜索
    if (req.query.createdAt) {
      sql += " AND `t`.`created_at` >= :start AND `t`.`created_at` <= :end";
      replacements.start = `${req.query.createdAt}`;
      replacements.end = `${req.query.createdAt.split(" ")[0]} 23:59:59`;
    }

    sequelize
      .query(sql, {
        replacements,
        type: QueryTypes.SELECT,
      })
      .then((result) => {
        res.send({
          msg: "查询商品类型数量成功",
          code: 1070,
          count: result[0].count,
        });
      })
      .catch((err) => {
        res.send({ msg: "查询商品类型数量失败", code: 1071 });
      });
  }
  //根据商品类型typeId查询商品类型数据
  getTypeByTypeId(req, res) {
    // res.send("ok");
    // console.log("req.query==>", req.query);

    let sql =
      "SELECT `ut`.`type_id` AS `typeId`, `ut`.`user_id` AS `userId`, `t`.`name` FROM `user_type` AS `ut` INNER JOIN `type` AS `t` ON `t`.`type_id` = `ut`.`type_id` AND `ut`.`user_id` = :userId AND `t`.`type_id` = :typeId";
    sequelize
      .query(sql, {
        replacements: {
          userId: req.userId,
          typeId: req.query.typeId,
        },
        type: QueryTypes.SELECT,
      })
      .then((result) => {
        res.send({
          msg: "根据商品类型typeId查询商品类型数据成功",
          code: 1080,
          result,
        });
      })
      .catch((err) => {
        res.send({ msg: "根据商品类型typeId查询商品类型数据失败", code: 1081 });
      });
  }
  //编辑商品类型
  editType(req, res) {
    // res.send("ok");
    model.Type.update(
      {
        name: req.body.name,
      },
      {
        where: {
          typeId: req.body.typeId,
        },
      }
    )
      .then((result) => {
        res.send({
          msg: "编辑商品类型成功",
          code: 1090,
          result,
        });
      })
      .catch((err) => {
        console.log("err==>", err);
        res.send({ msg: "编辑商品类型失败", code: 1091 });
      });
  }
  //确认删除商品类型
  removeType(req, res) {
    // console.log('req.body==>',req.body)
    // res.send('ok')
    model.Type.destroy({
      where: {
        typeId: {
          [Op.in]: req.body.typeIds,
        },
      },
    })
    model.UserType.destroy({
      where: {
        typeId: {
          [Op.in]: req.body.typeIds,
        },
      },
    })
      .then((result) => {
        console.log("result==>", result);
        res.send({ msg: "删除商品类型成功", code: 1100, result });
      })
      .catch((err) => {
        console.log("err==>", err);
        res.send({ msg: "删除商品类型失败", code: 1101 });
      });
  }
  //创建商品
  async postProduct(req, res) {
    let smallImg = await utils.uploadImg({
      base64: req.body.smallImg,
      type: req.body.smallImgType,
    });
    let largeImg = await utils.uploadImg({
      base64: req.body.largeImg,
      type: req.body.largeImgType,
    });
    console.log('smallImg==>',smallImg)
    console.log('largeImg==>',largeImg)
    //生成商品ID
    let productId = uuid.v1();

    //启动事务处理
    sequelize
      .transaction(async (t) => {
        // 1、创建商品数据
        await model.Product.create(
          {
            productId,
            name: req.body.name,
            date: req.body.date,
            price: Number(req.body.price),
            number: req.body.number,
            publisher: req.body.publisher,
            resource: Number(req.body.resource),
            smallImg,
            largeImg,
            desc: req.body.desc,
          },
          { transaction: t }
        );

        // 2、创建商品和商品类型关系数据
        await model.ProductType.create(
          {
            productId,
            typeId: req.body.region,
          },
          { transaction: t }
        );
        // 3、创建商品和用户的关系数据
        await model.UserProduct.create(
          {
            productId,
            userId: req.userId,
          },
          { transaction: t }
        );
      })
      .then((result) => {
        res.send({ msg: "发布商品成功", code: 1130 });
      })
      .catch((err) => {
        console.log("err==>", err);
        res.send({ msg: "发布商品失败", code: 1131 });
      });
  }
  //获取商品类型
  getType(req, res) {
    // res.send("ok1");

    let sql =
      "SELECT `ut`.`type_id` AS `typeId`, `ut`.`user_id` AS `userId`, `t`.`name`, `t`.`created_at` AS `createdAt` FROM `user_type` AS `ut` INNER JOIN `type` AS `t` ON `t`.`type_id` = `ut`.`type_id` AND `ut`.`user_id` = :userId";
    //替换sql语句的参数
    let replacements = {
      userId: req.userId,
    };
    sequelize
      .query(sql, {
        replacements,
        type: QueryTypes.SELECT,
      })
      .then((result) => {
        res.send({ msg: "查询商品类型成功", code: 1120, result });
      })
      .catch((err) => {
        res.send({ msg: "查询商品类型失败", code: 1121 });
      });
  }
  //查询商品
  findProduct(req, res) {
    // let sql = "SELECT `p`.`product_id`, `p`.`name` AS `product_name`, `p`.`price`, `p`.`status`, `p`.`desc`, `p`.`small_img`, `p`.`large_img`, `p`.`created_at`, `pt`.`type_id`, `t`.`name` FROM `product` AS `p` INNER JOIN `product_type` AS `pt` ON `pt`.`product_id` = `p`.`product_id` INNER JOIN `type` AS `t` ON `t`.`type_id` = `pt`.`type_id` INNER JOIN `user_product` AS `up` ON `up`.`product_id` = `p`.`product_id` AND `up`.`user_id` = 'ce4b2840-d19f-11ec-903b-e90dbac59cca' AND `p`.`name` LIKE '%菜%' AND `t`.`type_id` = '11606bf0-d357-11ec-921f-e1246f807204' AND `p`.`status` = 0 AND `p`.`created_at` >= '2022-05-16 00:00:00' AND `p`.`created_at` <= '2022-05-16 23:59:59' ORDER BY `p`.`created_at` DESC LIMIT 1, 1";
    //

    let sql =
      "SELECT `p`.`product_id` AS `productId`, `p`.`name`, `p`.`price`, `p`.`number`, `p`.`publisher`, `p`.`resource` AS `status`, `p`.`date`, `p`.`desc`, `p`.`small_img` AS `smallImg`, `p`.`large_img` AS `largeImg`, `p`.`large_img` AS `largeImg`, `p`.`created_at` AS `createdAt`, `pt`.`type_id` AS `typeId`, `t`.`name` AS `region` FROM `product` AS `p` INNER JOIN `product_type` AS `pt` ON `pt`.`product_id` = `p`.`product_id` INNER JOIN `type` AS `t` ON `t`.`type_id` = `pt`.`type_id` INNER JOIN `user_product` AS `up` ON `up`.`product_id` = `p`.`product_id` AND `up`.`user_id` = :userId";

    let replacements = {
      userId: req.userId,
      offset: Number(req.query.offset),
      limit: Number(req.query.limit),
    };

    //处理参数
    if (req.query.name) {
      replacements.name = `%${req.query.name}%`;
      sql += " AND `p`.`name` LIKE :name";
    }

    if (req.query.typeId != "-1") {
      replacements.typeId = req.query.typeId;
      sql += " AND `t`.`type_id` = :typeId";
    }

    if (req.query.status !== "") {
      replacements.status = Number(req.query.status);
      sql += " AND `p`.`resource` = :status";
    }

    if (req.query.createdAt) {
      replacements.start = req.query.createdAt + " 00:00:00";
      replacements.end = req.query.createdAt + " 23:59:59";
      sql += " AND `p`.`created_at` >= :start AND `p`.`created_at` <= :end";
    }

    sql += " ORDER BY `p`.`created_at` DESC LIMIT :offset, :limit";

    sequelize
      .query(sql, {
        replacements,
        type: QueryTypes.SELECT,
      })
      .then((result) => {
        res.send({ msg: "查询商品类型成功", code: 1140, result });
      })
      .catch((err) => {
        res.send({ msg: "查询商品类型失败", code: 1141 });
      });
  }
  //获取商品总数量
  getAllProductCount(req, res) {
    // let sql = "SELECT `p`.`product_id`, `p`.`name` AS `product_name`, `p`.`price`, `p`.`status`, `p`.`desc`, `p`.`small_img`, `p`.`large_img`, `p`.`created_at`, `pt`.`type_id`, `t`.`name` FROM `product` AS `p` INNER JOIN `product_type` AS `pt` ON `pt`.`product_id` = `p`.`product_id` INNER JOIN `type` AS `t` ON `t`.`type_id` = `pt`.`type_id` INNER JOIN `user_product` AS `up` ON `up`.`product_id` = `p`.`product_id` AND `up`.`user_id` = 'ce4b2840-d19f-11ec-903b-e90dbac59cca' AND `p`.`name` LIKE '%菜%' AND `t`.`type_id` = '11606bf0-d357-11ec-921f-e1246f807204' AND `p`.`status` = 0 AND `p`.`created_at` >= '2022-05-16 00:00:00' AND `p`.`created_at` <= '2022-05-16 23:59:59' ORDER BY `p`.`created_at` DESC LIMIT 1, 1";

    let sql =
      "SELECT COUNT(`p`.`product_id`) AS `count` FROM `product` AS `p` INNER JOIN `product_type` AS `pt` ON `pt`.`product_id` = `p`.`product_id` INNER JOIN `type` AS `t` ON `t`.`type_id` = `pt`.`type_id` INNER JOIN `user_product` AS `up` ON `up`.`product_id` = `p`.`product_id` AND `up`.`user_id` = :userId";

    let replacements = {
      userId: req.userId,
    };

    //处理参数
    if (req.query.name) {
      replacements.name = `%${req.query.name}%`;
      sql += " AND `p`.`name` LIKE :name";
    }

    if (req.query.typeId != "-1") {
      replacements.typeId = req.query.typeId;
      sql += " AND `t`.`type_id` = :typeId";
    }

    if (req.query.status !== "") {
      replacements.status = Number(req.query.status);
      sql += " AND `p`.`status` = :status";
    }

    if (req.query.createdAt) {
      replacements.start = req.query.createdAt + " 00:00:00";
      replacements.end = req.query.createdAt + " 23:59:59";
      sql += " AND `p`.`created_at` >= :start AND `p`.`created_at` <= :end";
    }

    sequelize
      .query(sql, {
        replacements,
        type: QueryTypes.SELECT,
      })
      .then((result) => {
        res.send({
          msg: "查询商品总数量成功",
          code: 1150,
          count: result[0].count,
        });
      })
      .catch((err) => {
        res.send({ msg: "查询商品总数量失败", code: 1151 });
      });
  }
  //修改商品上下架状态
  updateProductStatus(req, res) {
    model.Product.update(
      {
        resource: Number(req.body.status),
      },
      {
        where: {
          productId: req.body.productId,
        },
      }
    )
      .then((result) => {
        res.send({ msg: "修改商品上下架状态成功", code: 1160, result });
      })
      .catch((err) => {
        res.send({ msg: "修改商品上下架状态成功", code: 1160 });
      });
  }
  //删除商品
  removeProduct(req, res) {
    //1、删除商品基础表数据
    //2、删除商品和类型关系表数据
    //3、删除商品和用户表数据
    sequelize
      .transaction(async (t) => {
        //1、删除商品基础表数据
        await model.Product.destroy(
          {
            where: {
              productId: {
                [Op.in]: req.body.productIds,
              },
            },
          },
          { transaction: t }
        );

        //2、删除商品和类型关系表数据
        await model.ProductType.destroy(
          {
            where: {
              productId: {
                [Op.in]: req.body.productIds,
              },
            },
          },
          { transaction: t }
        );

        //3、删除商品和用户表数据
        await model.UserProduct.destroy(
          {
            where: {
              productId: {
                [Op.in]: req.body.productIds,
              },
            },
          },
          { transaction: t }
        );
      })
      .then(() => {
        res.send({ msg: "删除商品成功", code: 1170 });
      })
      .catch(() => {
        res.send({ msg: "删除商品失败", code: 1171 });
      });
  }
  //根据商品id查询商品数据
  getProductById(req, res) {
    let sql =
    "SELECT `p`.`product_id` AS `productId`, `p`.`name`, `p`.`price`, `p`.`number`, `p`.`publisher`, `p`.`resource` AS `status`, `p`.`date`, `p`.`desc`, `p`.`small_img` AS `smallImg`, `p`.`large_img` AS `largeImg`, `p`.`large_img` AS `largeImg`, `p`.`created_at` AS `createdAt`, `pt`.`type_id` AS `typeId`, `t`.`name` AS `region` FROM `product` AS `p` INNER JOIN `product_type` AS `pt` ON `pt`.`product_id` = `p`.`product_id` INNER JOIN `type` AS `t` ON `t`.`type_id` = `pt`.`type_id` AND `p`.`product_id` = :productId";
    sequelize
      .query(sql, {
        replacements: {
          productId: req.query.productId,
        },
        type: QueryTypes.SELECT,
      })
      .then((result) => {
        res.send({ msg: "查询商品成功", code: 1180, result });
      })
      .catch((err) => {
        res.send({ msg: "查询商品失败", code: 1181 });
      });
  }
  //编辑商品
  async editProduct(req, res) {
    // return res.send('ok');
    //保存商品基础数据表的数据
    console.log('req.body==>',req.body);
    let productData = { ...req.body };
    delete productData.productId;
    //判断是否存在图片修改
    //商品图片
    if (req.body.smallImg) {
      productData.smallImg = await utils.uploadImg({
        base64: req.body.smallImg,
        type: req.body.smallImgType,
      });
      delete productData.smallImgType;
    }

    //详情图片
    if (req.body.largeImg) {
      productData.largeImg = await utils.uploadImg({
        base64: req.body.largeImg,
        type: req.body.largeImgType,
      });

      delete productData.largeImgType;
    }

    //启动事务处理
    sequelize
      .transaction(async (t) => {
        //是否存在修改商品类型
        if (req.body.type) {
          //修改商品和商品类型关系表数据
          await model.ProductType.update(
            {
              typeId: req.body.type,
            },
            {
              where: {
                productId: req.body.productId,
              },
            },
            { transaction: t }
          );

          delete productData.type;
        }

        //是否存在修改商品基础表数据

        if (Object.keys(productData).length > 0) {
          //修改商品数据
          await model.Product.update(
            {
              ...productData,
            },
            {
              where: {
                productId: req.body.productId,
              },
            },
            { transaction: t }
          );
        }
      })
      .then(() => {
        res.send({ msg: "编辑商品成功", code: 1190 });
      })
      .catch((err) => {
        res.send({ msg: "编辑商品失败", code: 1191 });
      });
  }
  //获取用户信息
  getUserInfo(req, res) {
    model.User.findOne({
      attributes: ["email", "userImg"],
      where: {
        userId: req.userId,
      },
    })
      .then((result) => {
        res.send({ msg: "获取用户数据成功", code: 1200, result });
      })
      .catch((err) => {
        res.send({ msg: "获取用户数据失败", code: 1201 });
      });
  }
}
module.exports = new Controller();
